#include "MenuManager.h"


#include "../../Framework/SceneManager.h"
#include "../../GameConfig.h"
#include "../Level/LevelManager.h"
#include "../../Objects/Ghost/GhostObject.h"
#include "../../Player/PlayerInfo.h"
#include "../Splash/SplashManager.h"
#include "../../Data/GameData.h"
#include "../../Framework/SoundManager.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "Cocos2dxStore.h"
#include "../../IAP/SoomlaIAPEventHandler.h"
using namespace soomla;
#endif

bool MenuManager::m_isProcressing = false;

cocos2d::Scene* MenuManager::createScene()
{
	auto scene = Scene::create();
	auto layer = MenuManager::create();
	scene->addChild(layer);

	return scene;
}

MenuManager::~MenuManager()
{
	CC_SAFE_DELETE(m_timeline);
	SpriteFrameCache::getInstance()->removeUnusedSpriteFrames();
	SpriteFrameCache::getInstance()->removeSpriteFrames();
	TextureCache::getInstance()->removeAllTextures();
}

bool MenuManager::init()
{
	if (!Layer::init())
	{
		return false;
	}
	this->setKeypadEnabled(true);
	m_isProcressing = false;
	m_isOpenSetting = false;
	m_screenSize = Director::getInstance()->getVisibleSize();

	initalize();
	return true;
}

void MenuManager::initalize()
{
	m_node = CSLoader::getInstance()->createNode("MenuScene.csb");

	float scale = m_screenSize.height / m_node->getContentSize().height;
	m_node->setScale(scale);
	m_node->setAnchorPoint(Vec2(0.5f, 0.5f));
	m_node->setPosition(Vec2(m_screenSize.width / 2, m_screenSize.height / 2));

	initLayer();
	initBackground();
	initComponent();
	initButton();
	initGhostBanner();

	this->addChild(m_node);

	m_pnlHome->setVisible(true);
	m_pnlGuri->setVisible(false);
	m_pnlSetting->setVisible(false);
	m_pnlExit->setVisible(false);
	m_pnlPurchase->setVisible(false);

	m_timeline = CSLoader::createTimeline("MenuScene.csb");
	m_timeline->retain();

	m_node->runAction(m_timeline);
	m_timeline->gotoFrameAndPlay(0, 345, false);
}

void MenuManager::initBackground()
{
	auto background = Sprite::create("bg_home.png");

	float scaleX = m_screenSize.width / background->getContentSize().width;
	float scaleY = m_screenSize.height / background->getContentSize().height;

	background->setScale(scaleX, scaleY);
	background->setAnchorPoint(Vec2(0.5f, 0.5f));
	background->setPosition(Vec2(m_screenSize.width / 2, m_screenSize.height / 2));

	this->addChild(background);
}

void MenuManager::initLayer()
{
	m_pnlHome = m_node->getChildByName("pnlHome");
	m_pnlGuri = m_node->getChildByName("pnlGuri");
	m_pnlHelp = m_node->getChildByName("pnlHelp");
	m_pnlExit = m_node->getChildByName("pnlExit");
	m_pnlPurchase = m_node->getChildByName("pnlPurchase");
}

void MenuManager::initComponent()
{
	m_btnSetting = dynamic_cast<Button*>(m_pnlHome->getChildByTag(EMenuCocoTag::kMenuCoco_Button)->getChildByTag(EMenuCocoTag::kMenuCoco_btnSetting));
	m_pnlSetting = dynamic_cast<Node*>(m_pnlHome->getChildByName("Buttons")->getChildByName("clipSetting")->getChildByName("pnlSettings"));
    m_btnSetting->setPressedActionEnabled(true);

    
}

void MenuManager::initGhostBanner()
{
	Node* bannerGhost = m_pnlHome->getChildByName("sprBanner")->getChildByName("bannerGhost");
	GhostObject* ghost = new GhostObject();
	ghost->initalize(EGhostColor::kGhostColor_Orange, EGhostFaceState::kGhostFaceState_Full, EGhostHandState::kGhostHandState_None, EGhostEyeColor::kGhostEyeColor_Random,
		Vec2::ZERO, 0.55f, true);
	bannerGhost->addChild(ghost);
}

void MenuManager::initButton()
{
#pragma region HOME
	//Setting
	Button* btnSetting = dynamic_cast<Button*>(m_btnSetting);
	btnSetting->addClickEventListener(CC_CALLBACK_1(MenuManager::tapSetting, this));
    btnSetting->setPressedActionEnabled(true);
    
	//Hard - Normal - Easy
	Node* button = m_pnlHome->getChildByTag(EMenuCocoTag::kMenuCoco_Button);

	Button* btnHard = dynamic_cast<Button*>(button->getChildByTag(EMenuCocoTag::kMenuCoco_btnHard));
	Button* btnNormal = dynamic_cast<Button*>(button->getChildByTag(EMenuCocoTag::kMenuCoco_btnNormal));
	Button* btnEasy = dynamic_cast<Button*>(button->getChildByTag(EMenuCocoTag::kMenuCoco_btnEasy));

	btnHard->addClickEventListener(CC_CALLBACK_1(MenuManager::tapMode, this));
	btnNormal->addClickEventListener(CC_CALLBACK_1(MenuManager::tapMode, this));
	btnEasy->addClickEventListener(CC_CALLBACK_1(MenuManager::tapMode, this));
    
    btnHard->setPressedActionEnabled(true);
    btnNormal->setPressedActionEnabled(true);
    btnEasy->setPressedActionEnabled(true);
	// purchase
	Button* btnPurchase = dynamic_cast<Button*>(button->getChildByTag(EMenuCocoTag::kMenuCoco_btnPurchase));
	btnPurchase->addClickEventListener(CC_CALLBACK_1(MenuManager::tapPurchase, this));
    btnPurchase->setPressedActionEnabled(true);
	// facebook - twitter - guri
	Button* btnFacebook = dynamic_cast<Button*>(button->getChildByName("btnFacebook"));
	Button* btnTwitter = dynamic_cast<Button*>(button->getChildByName("btnTwitter"));
	Button* btnGuri = dynamic_cast<Button*>(button->getChildByName("btnGuri"));

	btnFacebook->addClickEventListener(CC_CALLBACK_1(MenuManager::tapFacebook, this));
	btnTwitter->addClickEventListener(CC_CALLBACK_1(MenuManager::tapTwitter, this));
	btnGuri->addClickEventListener(CC_CALLBACK_1(MenuManager::tapGuri, this));

    btnFacebook->setPressedActionEnabled(true);
    btnTwitter->setPressedActionEnabled(true);
    btnGuri->setPressedActionEnabled(true);
	// Help - sound - music
	Button* btnHelp = dynamic_cast<Button*>(m_pnlSetting->getChildByName("btnHelp"));
	Button* btnAudio = dynamic_cast<Button*>(m_pnlSetting->getChildByName("btnAudio"));
	Button* btnMusic = dynamic_cast<Button*>(m_pnlSetting->getChildByName("btnMusic"));

	btnHelp->addClickEventListener(CC_CALLBACK_1(MenuManager::tapHelp, this));
	btnAudio->addClickEventListener(CC_CALLBACK_1(MenuManager::tapSound, this));
	btnMusic->addClickEventListener(CC_CALLBACK_1(MenuManager::tapMusic, this));
#pragma endregion

#pragma region GURI
	Button* btnCancel = dynamic_cast<Button*>(m_pnlGuri->getChildByName("sprBackground")->getChildByName("btnCancel"));
	btnCancel->addClickEventListener(CC_CALLBACK_1(MenuManager::tapCloseGuri, this));
#pragma endregion

#pragma region HELP
	Button* btnCancelhelp = dynamic_cast<Button*>(m_pnlHelp->getChildByName("sprBackground")->getChildByName("btnCancel"));
	btnCancelhelp->addClickEventListener(CC_CALLBACK_1(MenuManager::tapCloseHelp, this));
#pragma endregion

#pragma region EXIT
	Button* btnYesExit = dynamic_cast<Button*>(m_pnlExit->getChildByName("sprBackground")->getChildByName("btnYes"));
	Button* btnNoExit = dynamic_cast<Button*>(m_pnlExit->getChildByName("sprBackground")->getChildByName("btnNo"));

	btnYesExit->addClickEventListener(CC_CALLBACK_1(MenuManager::tapYesExit, this));
	btnNoExit->addClickEventListener(CC_CALLBACK_1(MenuManager::tapNoExit, this));
#pragma endregion

#pragma region PURCHASE
	Button* btnPurchaseEasy = dynamic_cast<Button*>(m_pnlPurchase->getChildByName("sprBackground")->getChildByName("btnEasy"));
	Button* btnPurchaseNormal = dynamic_cast<Button*>(m_pnlPurchase->getChildByName("sprBackground")->getChildByName("btnNormal"));
	Button* btnPurchaseHard = dynamic_cast<Button*>(m_pnlPurchase->getChildByName("sprBackground")->getChildByName("btnHard"));
	Button* btnPurchaseClose = dynamic_cast<Button*>(m_pnlPurchase->getChildByName("sprBackground")->getChildByName("btnCancel"));

	btnPurchaseEasy->addClickEventListener(CC_CALLBACK_1(MenuManager::tapPurchaseEasy, this));
	btnPurchaseNormal->addClickEventListener(CC_CALLBACK_1(MenuManager::tapPurchaseNormal, this));
	btnPurchaseHard->addClickEventListener(CC_CALLBACK_1(MenuManager::tapPurchaseHard, this));
	btnPurchaseClose->addClickEventListener(CC_CALLBACK_1(MenuManager::tapClosePurchase, this));
    
    btnPurchaseEasy->setPressedActionEnabled(true);
    btnPurchaseNormal->setPressedActionEnabled(true);
    btnPurchaseHard->setPressedActionEnabled(true);
    btnPurchaseClose->setPressedActionEnabled(true);
#pragma endregion
}

#pragma region IAP
void MenuManager::onEnter()
{
	Layer::onEnter();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	/* __NotificationCenter::getInstance()->addObserver(this,
			 callfuncO_selector(MenuManager::updateFullVersion),
			 EVENT_ON_CURRENCY_BALANCE_CHANGED, NULL);*/
#endif
}

void MenuManager::onExit()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	/*  __NotificationCenter::getInstance()->removeObserver(this, EVENT_ON_CURRENCY_BALANCE_CHANGED);*/
#endif
	Layer::onExit();
}

void MenuManager::updateFullVersion(Ref *pBalance)
{
	/*if(m_iapPackage > 0)
	{
	switch(m_iapPackage)
	{
	case 1:
	PlayerInfo::getInstance()->iap->setModeFullVersion(EGameMode::kMode_Easy, true);
	break;
	case 2:
	PlayerInfo::getInstance()->iap->setModeFullVersion(EGameMode::kMode_Normal, true);
	break;
	case 3:
	PlayerInfo::getInstance()->iap->setModeFullVersion(EGameMode::kMode_Hard, true);
	break;
	}
	}*/
}
#pragma endregion

#pragma region Panel home tap
void MenuManager::tapMode(cocos2d::Ref *pSender)
{
	if (!m_isProcressing)
	{
		Button* btn = dynamic_cast<Button*>(pSender);
		switch (btn->getTag())
		{
		case EMenuCocoTag::kMenuCoco_btnHard:
			LevelManager::s_mode = EGameMode::kMode_Hard;

			break;
		case EMenuCocoTag::kMenuCoco_btnNormal:
			LevelManager::s_mode = EGameMode::kMode_Normal;

			break;
		case EMenuCocoTag::kMenuCoco_btnEasy:
			LevelManager::s_mode = EGameMode::kMode_Easy;

			break;
		}
		m_isProcressing = true;
        
        SoundManager::getInstance()->playSound(ESound::kSound_Click);
        SceneManager::getInstance()->changeScene(this, EScene::kScene_Level);
	}
}

void MenuManager::tapSetting(cocos2d::Ref *pSender)
{
	if (!m_isOpenSetting && !m_pnlSetting->isVisible())
	{
        SoundManager::getInstance()->playSound(ESound::kSound_SettingButton);
        
		m_pnlSetting->setVisible(true);
		m_timeline->gotoFrameAndPlay(400, 415, false);

		this->runAction(Sequence::create(DelayTime::create(15.0f / 60.0f),
			CallFuncN::create(CC_CALLBACK_0(MenuManager::setOpenSettingProperty, this)), NULL));
	}
	if (m_isOpenSetting && m_pnlSetting->isVisible())
	{
        SoundManager::getInstance()->playSound(ESound::kSound_SettingButton);
        
		m_timeline->gotoFrameAndPlay(420, 435, false);
		this->runAction(Sequence::create(DelayTime::create(15.0f / 60.0f),
			CallFuncN::create(CC_CALLBACK_0(MenuManager::setOpenSettingProperty, this)), NULL));
	}
}

void MenuManager::tapFacebook(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
}

void MenuManager::tapTwitter(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
}

void MenuManager::tapGuri(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	m_pnlHome->setVisible(false);
	m_pnlGuri->setVisible(true);

	m_timeline->gotoFrameAndPlay(0, 80, false);
}

void MenuManager::tapHelp(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	m_pnlHome->setVisible(false);
	m_pnlHelp->setVisible(true);

	m_timeline->gotoFrameAndPlay(0, 80, false);
}

void MenuManager::tapSound(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
    
    if(CocosDenshion::SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying())
        CocosDenshion::SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
    else
        CocosDenshion::SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}

void MenuManager::tapMusic(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
    
    if(CocosDenshion::SimpleAudioEngine::getInstance()->getEffectsVolume() == 0.0f)
        CocosDenshion::SimpleAudioEngine::getInstance()->setEffectsVolume(1.0f);
    else
        CocosDenshion::SimpleAudioEngine::getInstance()->setEffectsVolume(0.0f);
}

void MenuManager::tapPurchase(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	m_pnlHome->setVisible(false);
	m_pnlPurchase->setVisible(true);

	m_timeline->gotoFrameAndPlay(0, 80, false);
}
#pragma endregion

#pragma region Panel guri tap
void MenuManager::tapCloseGuri(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	m_timeline->gotoFrameAndPlay(200, 240, false);
	auto func2 = CallFuncN::create(CC_CALLBACK_0(MenuManager::openPanelHome, this));
	this->runAction(Sequence::create(DelayTime::create(40.0f / 60.0f), func2,
		NULL));
}
#pragma endregion

#pragma region Panel help tap
void MenuManager::tapCloseHelp(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	m_timeline->gotoFrameAndPlay(200, 240, false);
	auto func2 = CallFuncN::create(CC_CALLBACK_0(MenuManager::openPanelHome, this));
	this->runAction(Sequence::create(DelayTime::create(40.0f / 60.0f), func2,
		NULL));
}
#pragma endregion

#pragma region Panel Exit tap
void MenuManager::tapYesExit(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	Director::getInstance()->end();
	exit(0);
}

void MenuManager::tapNoExit(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	openPanelHome();
}
#pragma endregion

#pragma region Panel purchase tap
void MenuManager::tapPurchaseEasy(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	CCError *soomlaError = NULL;
	CCStoreInventory::sharedStoreInventory()->buyItem("iap_easy", &soomlaError);
	if (soomlaError)
	{
		CCSoomlaUtils::logException("Error IAP on menu scene:", soomlaError);
		return;
	}

	PlayerInfo::getInstance()->iap->setModeFullVersion(EGameMode::kMode_Easy, true);
#endif
}

void MenuManager::tapPurchaseNormal(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	CCError *soomlaError = NULL;
	CCStoreInventory::sharedStoreInventory()->buyItem("iap_normal", &soomlaError);
	if (soomlaError)
	{
		CCSoomlaUtils::logException("Error IAP on menu scene:", soomlaError);
		return;
	}

	PlayerInfo::getInstance()->iap->setModeFullVersion(EGameMode::kMode_Normal, true);
#endif
}

void MenuManager::tapPurchaseHard(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	CCError *soomlaError = NULL;
	CCStoreInventory::sharedStoreInventory()->buyItem("iap_hard", &soomlaError);
	if (soomlaError)
	{
		CCSoomlaUtils::logException("Error IAP on menu scene:", soomlaError);
		return;
	}

	PlayerInfo::getInstance()->iap->setModeFullVersion(EGameMode::kMode_Hard, true);
#endif
}

void MenuManager::tapClosePurchase(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
	m_timeline->gotoFrameAndPlay(200, 240, false);
	auto func2 = CallFuncN::create(CC_CALLBACK_0(MenuManager::openPanelHome, this));
	this->runAction(Sequence::create(DelayTime::create(40.0f / 60.0f), func2,
		NULL));
}
#pragma endregion

void MenuManager::openPanelHome()
{
	m_isOpenSetting = false;

	m_pnlHome->setVisible(true);
	m_pnlSetting->setVisible(false);
	m_pnlExit->setVisible(false);
	m_pnlGuri->setVisible(false);
	m_pnlHelp->setVisible(false);
	m_pnlPurchase->setVisible(false);

	m_timeline->gotoFrameAndPlay(0, 345, false);
}

void MenuManager::setOpenSettingProperty()
{
	m_isOpenSetting = !m_isOpenSetting;

	if (!m_isOpenSetting)
		m_pnlSetting->setVisible(false);
}

void MenuManager::onKeyReleased(EventKeyboard::KeyCode keyCode, cocos2d::Event *event)
{
	if (keyCode == EventKeyboard::KeyCode::KEY_BACKSPACE) 
	{
		m_pnlHome->setVisible(false);
		m_pnlExit->setVisible(true);

		m_timeline->gotoFrameAndPlay(0, 80, false);
	}
}
